package com.oracle.lingshangejia.activity.special;

import android.app.DatePickerDialog;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.oracle.lingshangejia.Constant;
import com.oracle.lingshangejia.R;
import com.oracle.lingshangejia.adapter.special.ETZYArchivesExtendableListAdapter;
import com.oracle.lingshangejia.bean.DataBean;
import com.oracle.lingshangejia.bean.User;
import com.oracle.lingshangejia.dialog.LoadingViewDialog;
import com.oracle.lingshangejia.model.OkgoNetwork;
import com.oracle.lingshangejia.utils.MyLogger;
import com.oracle.lingshangejia.utils.MyToast;
import com.oracle.lingshangejia.utils.ObserverOnNext;
import com.oracle.lingshangejia.utils.RxUtils;

import org.json.JSONObject;

import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

//儿童中医药健康管理服务记录
public class ErTongZhongYiActivity extends AppCompatActivity {
    private ExpandableListView expandableListView;
    private ETZYArchivesExtendableListAdapter archivesExtendableListAdapter;

    private static int[] childItems = { R.layout.etzy_childsmedicine_item_1};
    // 用于存放折叠的视图
    private View[] viewss  = new View[childItems.length];

    private Spinner ageSpinner;
    private int i =1; //默认

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.etzy_add_archives_activity);
        initBasic();
        ageSpinner = findViewById(R.id.archives_ageOfTheMoon);

        expandableListView = findViewById(R.id.expend_list);
        expandableListView.setGroupIndicator(null);
        String[] archivesStr = getResources().getStringArray(R.array.etzy_archives);
        archivesExtendableListAdapter = new ETZYArchivesExtendableListAdapter(archivesStr);

        for(int i = 0; i < viewss.length; i++) {
            viewss[i] = LayoutInflater.from(expandableListView.getContext()).inflate(childItems[i], expandableListView, false);
        }
        archivesExtendableListAdapter.setConvertViews(viewss);
        expandableListView.setAdapter(archivesExtendableListAdapter);
        // 添加末尾提交按钮
        View foot = LayoutInflater.from(this).inflate(R.layout.archives_foot_submit, null);
        expandableListView.addFooterView(foot);

//        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
//            @Override
//            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
//                return checkBasicInfoIsError();
//            }
//        });
//
//        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
//            @Override
//            public void onGroupExpand(int groupPosition) {
//                int count = expandableListView.getExpandableListAdapter().getGroupCount();
//                for (int i = 0; i < count; i++) {
//                    if (i != groupPosition) {
//                        expandableListView.collapseGroup(i);
//                    }
//                }
//            }
//        });
        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                // 页面没加载时不折叠
                if(viewss == null)
                    return;
                int count = expandableListView.getExpandableListAdapter().getGroupCount();
                for (int i = 0; i < count; i++) {
                    if (i != groupPosition) {
                        expandableListView.collapseGroup(i);
                    }
                }

            }
        });

        ageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //取得被选中的列表项的文字
                String age = parent.getItemAtPosition(position).toString();
                for(View v:viewss) {
                    System.out.println("视图：" + v);
                }
                TableLayout healthManagement1 = viewss[0].findViewById(R.id.childsmedicine_healthManagement1);
                TableLayout healthManagement2 = viewss[0].findViewById(R.id.childsmedicine_healthManagement3);
                TableLayout healthManagement3 = viewss[0].findViewById(R.id.childsmedicine_healthManagement5);

                if("1 六月".equals(age)) {
                    i=1;
                    healthManagement1.setVisibility(View.VISIBLE);
                    healthManagement2.setVisibility(View.GONE);
                    healthManagement3.setVisibility(View.GONE);
                }
                if("2 十二月".equals(age)) {
                    i =1;
                    healthManagement1.setVisibility(View.VISIBLE);
                    healthManagement2.setVisibility(View.GONE);
                    healthManagement3.setVisibility(View.GONE);
                }
                if("3 十八月".equals(age)) {
                    i=2;
                    healthManagement2.setVisibility(View.VISIBLE);

                    healthManagement1.setVisibility(View.GONE);
                    healthManagement3.setVisibility(View.GONE);
                }
                if("4 二十四月".equals(age)) {
                    i=2;
                    healthManagement2.setVisibility(View.VISIBLE);

                    healthManagement1.setVisibility(View.GONE);
                    healthManagement3.setVisibility(View.GONE);
                }
                if("5 三十月".equals(age)) {
                    i=3;
                    healthManagement3.setVisibility(View.VISIBLE);

                    healthManagement2.setVisibility(View.GONE);
                    healthManagement1.setVisibility(View.GONE);
                }
                if("6 三十六月".equals(age)) {
                    i=3;
                    healthManagement3.setVisibility(View.VISIBLE);
                    healthManagement2.setVisibility(View.GONE);
                    healthManagement1.setVisibility(View.GONE);
                }
                // 获取数据后只留第一个展开，其余关闭
                int count = expandableListView.getExpandableListAdapter().getGroupCount();
                for (int i = 0; i < count; i++) {
                    if(i == 0) {
                        expandableListView.expandGroup(i);
                    } else {
                        expandableListView.collapseGroup(i);
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        // 页面加载完展开所有数据，用于获取视图数据
        int count = expandableListView.getExpandableListAdapter().getGroupCount();
        for (int i = 0; i < count; i++) {
            expandableListView.expandGroup(i);
        }

        expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
            @Override
            public void onGroupCollapse(int groupPosition) {
                View[] views = ((ETZYArchivesExtendableListAdapter) expandableListView.getExpandableListAdapter()).getConvertViews();
                View view = views[groupPosition];
                if (view == null) {
                    return;
                }
                Map<String, String> values = null;
                switch (groupPosition) {
                  /*  case 0:
                        values = getBasicInfoValues();
                        break;*/
                    case 0:
                        values = getSixMouthsHealthManagementofChineseMedicineValues(view);
                        break;

                }


            }
        });

        expandableListView.expandGroup(0);

    }
    /**
     * 检查用户名、身份证号和本人联系电话是否正确填写
     *
     * @return 数据不正确返回true，正确返回false
     */
    private boolean checkBasicInfoIsError() {
        Map<String, String> basicInforValues = getBasicInfoValues();
        String xm = (String) basicInforValues.get("xm");
        // 姓名非空验证
        if (xm == null || xm.length() == 0) {
            Toast.makeText(getApplicationContext(), "姓名必须填写", Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }



    /**
     * 获取基本信息数据
     */
    private Map<String, String> getBasicInfoValues() {
        View[] views = ((ETZYArchivesExtendableListAdapter) expandableListView.getExpandableListAdapter()).getConvertViews();
        View view = views[0];
        Map<String, String> params = new HashMap<>();
        // 姓名
        String name = "";
        //居民id
        String residentID="";
        //医生ID
        String doctorID="";
        //月龄
        String age="";

        residentID = ((EditText) view.findViewById(R.id.childsmedicine_residentID)).getText().toString().trim();

        doctorID = ((EditText) view.findViewById(R.id.childsmedicine_doctorID)).getText().toString().trim();

        name = ((EditText) view.findViewById(R.id.childsmedicine_username)).getText().toString().trim();
        age = ((Spinner) findViewById(R.id.archives_ageOfTheMoon)).getSelectedItem().toString().trim();
        age = age.substring(0, age.indexOf(" "));
        params.put("xm", name);
        params.put("jmid", residentID);
        params.put("ysid", doctorID);
        params.put("yl", age);

        return params;
    }

    /**
     * 获取6月龄儿童中医药健康管理服务信息数据
     */
    private Map<String, String> getSixMouthsHealthManagementofChineseMedicineValues(View view) {
        Map<String, String> params = new HashMap<>();
        // 随访日期
        String date1 = "";
        // 中医药健康管理服务
        String healthManagement1 = "";
        // 中医药健康管理服务其他
        String otherhealthManagement1 = "";
        // 下次随访日期
        String nextdate1 = "";
        // 随访医生签名
        String doctorname1 = "";
        String date3 = "";
        // 中医药健康管理服务
        // 中医药健康管理服务其他
        String otherhealthManagement3 = "";
        String healthManagement3 = "";
        // 中医药健康管理服务
        String healthManagement5 = "";
        // 中医药健康管理服务其他
        String otherhealthManagement5 = "";

        //date1  = ((TextView) view.findViewById(R.id.childsmedicine_date1)).getText().toString().trim();

        View[] healthManagement1Views = getViews(view.findViewById(R.id.childsmedicine_healthManagement1));
        for (int i = 0; i < healthManagement1Views.length; i++) {
            if (healthManagement1Views[i] instanceof CheckBox) {
                CheckBox cb = (CheckBox) healthManagement1Views[i];
                if (cb.isChecked()) {
                    String s = cb.getText().toString().trim();
                    s = s.substring(0, s.indexOf(" "));
                    healthManagement1 += s;
                    healthManagement1 += ",";
                }
            }
        }
        if (healthManagement1.length() != 0) {
            healthManagement1 = healthManagement1.substring(0, healthManagement1.length() - 1);
        }
        otherhealthManagement1 = ((EditText) view.findViewById(R.id.childsmedicine_health_other_text1)).getText().toString().trim();

        nextdate1  = ((TextView) view.findViewById(R.id.childsmedicine_nextDate1)).getText().toString().trim();
        doctorname1 = ((EditText) view.findViewById(R.id.childsmedicine_doctorName1)).getText().toString().trim();
       // params.put("sfrq", date1);
        //月龄
        String age="";
        age = ((Spinner) findViewById(R.id.archives_ageOfTheMoon)).getSelectedItem().toString().trim();
        age = age.substring(0, age.indexOf(" "));
        params.put("yl", age); //月龄
        if (i==1){
        params.put("zyyjkglfw", healthManagement1);//中医健康服务
        params.put("zyyjkglfwQt", otherhealthManagement1);//中医健康服务其他内容
             }
        params.put("scsfsj", nextdate1);//下次随访日期
        params.put("sfYsqm", doctorname1); //签名

        View[] healthManagement3Views = getViews(view.findViewById(R.id.childsmedicine_healthManagement3));
        for (int i = 0; i < healthManagement3Views.length; i++) {
            if (healthManagement3Views[i] instanceof CheckBox) {
                CheckBox cb = (CheckBox) healthManagement3Views[i];
                if (cb.isChecked()) {
                    String s = cb.getText().toString().trim();
                    s = s.substring(0, s.indexOf(" "));
                    healthManagement3 += s;
                    healthManagement3 += ",";
                }
            }
        }
        if (healthManagement3.length() != 0) {
            healthManagement3 = healthManagement3.substring(0, healthManagement3.length() - 1);
        }
        otherhealthManagement3 = ((EditText) view.findViewById(R.id.childsmedicine_health_other_text3)).getText().toString().trim();

        if (i==2) {
            params.put("zyyjkglfw", healthManagement3);//中医健康服务
            params.put("zyyjkglfwQt", otherhealthManagement3);//中医健康服务其他内容
        }

        View[] healthManagement5Views = getViews(view.findViewById(R.id.childsmedicine_healthManagement5));
        for (int i = 0; i < healthManagement5Views.length; i++) {
            if (healthManagement5Views[i] instanceof CheckBox) {
                CheckBox cb = (CheckBox) healthManagement5Views[i];
                if (cb.isChecked()) {
                    String s = cb.getText().toString().trim();
                    s = s.substring(0, s.indexOf(" "));
                    healthManagement5 += s;
                    healthManagement5 += ",";
                }
            }
        }
        if (healthManagement5.length() != 0) {
            healthManagement5 = healthManagement5.substring(0, healthManagement5.length() - 1);
        }
        otherhealthManagement5 = ((EditText) view.findViewById(R.id.childsmedicine_health_other_text5)).getText().toString().trim();

        if (i == 3) {
            params.put("zyyjkglfw", healthManagement5);//中医健康服务
            params.put("zyyjkglfwQt", otherhealthManagement5);//中医健康服务其他内容
        }

        mValues.putAll(params);
        return params;
    }

    /**
     * Toolbar的事件---返回
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 点击日期选择框弹出DatePickerDialog
     */
    private Calendar calendar;
    private DatePickerDialog dialog;

    public void onTimeViewClick(final View v) {
        calendar = Calendar.getInstance();
        dialog = new DatePickerDialog(ErTongZhongYiActivity.this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year,
                                          int monthOfYear, int dayOfMonth) {
                        TextView tv = (TextView) v;
                        String month;
                        String day;
                        if (monthOfYear <9){
                            month = "0"+(monthOfYear+1);
                        }else {
                            month = ""+(monthOfYear+1);
                        }
                        if (dayOfMonth <10){
                            day = "0"+dayOfMonth;
                        }else {
                            day = dayOfMonth + "";
                        }
                        tv.setText(year + "-" + month  + "-" + day);
                    }
                }, calendar.get(Calendar.YEAR), calendar
                .get(Calendar.MONTH), calendar
                .get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    /**
     * 6月龄中医药健康管理服务按钮点击事件
     */
    public void onHealthManagementClick1(View view) {
        CheckBox cb = (CheckBox) view;
        EditText et = findViewById(R.id.childsmedicine_health_other_text1);
        if (cb.isChecked()) {
            et.setEnabled(true);
            et.setFocusable(true);
            et.setFocusableInTouchMode(true);
            et.requestFocus();
        } else {
            et.setText("");
            et.setEnabled(false);
        }
    }



    /**
     * 18月龄中医药健康管理服务按钮点击事件
     */
    public void onHealthManagementClick3(View view) {
        CheckBox cb = (CheckBox) view;
        EditText et = findViewById(R.id.childsmedicine_health_other_text3);
        if (cb.isChecked()) {
            et.setEnabled(true);
            et.setFocusable(true);
            et.setFocusableInTouchMode(true);
            et.requestFocus();
        } else {
            et.setText("");
            et.setEnabled(false);
        }
    }


    /**
     * 30月龄中医药健康管理服务按钮点击事件
     */
    public void onHealthManagementClick5(View view) {
        CheckBox cb = (CheckBox) view;
        EditText et = findViewById(R.id.childsmedicine_health_other_text5);
        if (cb.isChecked()) {
            et.setEnabled(true);
            et.setFocusable(true);
            et.setFocusableInTouchMode(true);
            et.requestFocus();
        } else {
            et.setText("");
            et.setEnabled(false);
        }
    }



    /**
     * 获取子视图
     */
    private View[] views;

    private View[] getViews(View view) {
        views = new View[0];
        parseView(view);
        return views;
    }

    private void parseView(View view) {
        if (view instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) view;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View v = vg.getChildAt(i);
                parseView(v);
            }
        } else {
            views = Arrays.copyOf(views, views.length + 1);
            views[views.length - 1] = view;
        }
    }



    /**
     * 提交数据
     */
    public void onClickSubmit(View view) {
        showLoading();
        int count = expandableListView.getExpandableListAdapter().getGroupCount();
        for (int i = 0; i < count; i++) {
            expandableListView.collapseGroup(i);
        }
        Observable.create(new ObservableOnSubscribe<DataBean>() {
            @Override
            public void subscribe(ObservableEmitter<DataBean> emitter) throws Exception {
                JSONObject jsonObject = new JSONObject(mValues);
                MyLogger.i(jsonObject.toString());
                String json = OkgoNetwork.post(url,jsonObject.toString());
                MyLogger.i(json);
                Gson gson = new Gson();
                emitter.onNext(gson.fromJson(json, DataBean.class));

            }
        }).compose(RxUtils.io_main()).subscribe(new ObserverOnNext<DataBean>() {
            @Override
            public void onNext(DataBean dataBean) {
                if (dataBean.getCode()==0){
                    MyToast.show("提交成功");
                    finish();
                }else {
                    MyToast.show(dataBean.getMsg());
                }
                dismissLoading();

            }
        });

    }


    //新
    private Map<Object,Object> mValues = new HashMap<>();
    private  String url = Constant.baseurl+"online/etzyyjkgljl/save";
    private LoadingViewDialog mLoadingView;
    //整合专项  基础 修改
    private void initBasic(){
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        Toolbar toolbar = (Toolbar)findViewById(com.oracle.children.R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mValues.put("token", User.getToken());
        mValues.put("jmId",getIntent().getIntExtra("jmid", 0) );
        mValues.put("userId", User.getUserId());//社区医生id;
        mValues.put("mark", 1);
        //随访id
        int id = getIntent().getIntExtra("id", 0);
        if (id !=0){
            mValues.put("sfjlId", id);
            mValues.put("id", id);
        }
    }



    public void showLoading(){
        mLoadingView = new LoadingViewDialog();
        mLoadingView.show(getSupportFragmentManager(),"" );
    }
    public void dismissLoading(){
        if (mLoadingView != null){
            mLoadingView.dismiss();
        }

    }

}
